<template>
    <div class="content-panel">
        <base-form :fields="fields" v-model="form" ref="formRef" :readonly="!editing"> </base-form>
        <div class="text-center">
            <template v-if="!editing">
                <el-button type="primary" @click="startEdit">编辑</el-button>
                <el-button @click="close">关闭</el-button>
            </template>
            <template v-else>
                <el-button type="primary" @click="doSave">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </template>
        </div>
    </div>
</template>
<script setup>
import https from "@/utils/https";
import { ElMessage } from "element-plus";
import { onMounted } from "vue";
import * as _ from "lodash";

const emits = defineEmits(["close", "change"]);
const props = defineProps({
    item: Object,
});
const fields = ref([
    { label: "设备", prop: "deviceCode", type: "select", options: loadDevices, required: true, filterable: true, change: deviceSelected },
    { label: "上数间隔", prop: "interval", required: true, type: "number", unit: "S" },
    {
        label: "属性",
        prop: "fields",
        type: "editTable",
        showIndex: true,
        showNew: false,
        withDelete: false,
        height: "70vh",
        fields: [
            { label: "属性编码", prop: "code", required: true, type: "text" },
            { label: "属性名称", prop: "name", type: "text" },
            {
                label: "属性类型",
                prop: "type",
                type: "select",
                options: [
                    { label: "字符串", value: "string" },
                    { label: "整数", value: "int" },
                    { label: "小数", value: "float" },
                    { label: "布尔值", value: "boolean" },
                ],
                width: "200px",
                change: (val, row) => {
                    if (val == "string") {
                        row.valueType = "fixed";
                    } else {
                        row.valueType = "rand";
                        row.value = 0;
                        row.maxValue = 1000;
                    }
                },
            },
            {
                label: "属性值类型",
                prop: "valueType",
                type: "select",
                width: "240px",
                disabled: (val, row) => row.type == "string",
                options: [
                    { label: "固定值", value: "fixed" },
                    { label: "随机值", value: "rand" },
                    { label: "随机递增", value: "randAdd" },
                ],
            },
            {
                label: "值",
                prop: "value",
                class: "d-flex",
                placeholder: (row) => (row.valueType == "fixed" ? "请输入属性值" : "请输入最小值"),
                width: "400px",
                sub: { label: "最大值", prop: "maxValue", show: (row) => row.valueType != "fixed", placeholder: "请输入最大值" },
            },
        ],
        required: true,
        buttons: [
            {
                label: "重新同步",
                action: loadFields,
                type: "primary",
            },
        ],
    },
]);

const form = ref({
    interval: 60,
});
const formRef = ref();
const editing = ref(false);
const bakForm = ref();

onMounted(() => {
    if (props.item?.id) {
        https.get("/manager/device-simulation/detail/" + props.item.id).then((resp) => {
            form.value = resp;
            editing.value = false;
        });
    } else {
        editing.value = true;
    }
});

function loadFields() {
    https.get("/manager/device-model/fields", { modelId: form.value.modelId }).then((resp) => {
        let fields = resp
            .filter((item) => item.type == 0)
            .map((item) => {
                return {
                    code: item.code,
                    name: item.name,
                    type: "int",
                    valueType: "rand",
                    value: 0,
                    maxValue: 1000,
                };
            });

        // 比较模型字段与现有字段差异，只处理新增字段
        let nowFields = [];
        form.value.fields.forEach((field) => nowFields.push(field.code));

        fields.forEach((field) => {
            if (nowFields.includes(field.code)) {
                return;
            }

            form.value.fields.push(field);
        });

        ElMessage.success("加载成功");
    });
}

function deviceSelected(val, form, { item }) {
    form.deviceName = item.label;
    form.gatewayCode = item.gatewayCode;
    form.modelId = item.modelId;

    // 查询模型字段
    https.get("/manager/device-model/fields", { modelId: form.modelId }).then((resp) => {
        form.fields = resp
            .filter((item) => item.type == 0)
            .map((item) => {
                return {
                    code: item.code,
                    name: item.name,
                    type: "int",
                    valueType: "rand",
                    value: 0,
                    maxValue: 1000,
                };
            });
    });
}

function startEdit() {
    bakForm.value = _.cloneDeep(form.value);
    editing.value = true;
}

function cancel() {
    if (form.value.id) {
        form.value = bakForm.value;
        editing.value = false;
    } else {
        close();
    }
}

function doSave() {
    formRef.value.validate((res) => {
        if (!res) {
            return;
        }

        let params = form.value;
        let fields = params.fields;
        for (var i in fields) {
            var field = fields[i];
            if (!field.code || !field.name) {
                ElMessage.error("属性编码或名称不能为空");
                return;
            }
        }

        https.post("/manager/device-simulation/save", form.value).then((resp) => {
            ElMessage.success("操作成功");
            form.value = resp;
            editing.value = false;
            emits("change");
        });
    });
}

function loadDevices() {
    return https.post("/manager/device/query").then((resp) => {
        return resp.map((item) => {
            return {
                label: item.name,
                value: item.code,
                ...item,
            };
        });
    });
}

function close() {
    emits("close");
}
</script>
